package operation;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class AddOperationJDBC implements IOperation{
    @Override
    public void work() throws SQLException {
        System.out.println("增加学生消息");
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生学号");
        String studentId = sc.next();
        System.out.println("请输入学生姓名");
        String studentName = sc.next();
        System.out.println("请输入学生年龄");
        int age = sc.nextInt();
        System.out.println("请输入学生性别");
        String sex = sc.next();
        System.out.println("请输入学生身份证");
        String id = sc.next();
        System.out.println("请输入学生电话");
        String tele = sc.next();

        //创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java110?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("zkzsa123");

        Connection connection = dataSource.getConnection();

        //来判断是否有该学生

        String sql1 = "select * from student where studentId = ?";
        PreparedStatement statement1 = connection.prepareStatement(sql1);
        statement1.setObject(1,studentId);
        ResultSet rs = statement1.executeQuery();
        while(rs.next()){
            String stuid = rs.getString("studentId");
            if(stuid.equals(studentId)){
                System.out.println("已有该学生，无法插入");
                rs.close();
                statement1.close();
                connection.close();
                return;
            }
        }

        String sql = "insert into student value(?,?,?,?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setObject(1,studentId);
        statement.setObject(2,studentName);
        statement.setObject(3,age);
        statement.setObject(4,sex);
        statement.setObject(5,id);
        statement.setObject(6,tele);

        int n = statement.executeUpdate();
        rs.close();
        statement.close();
        connection.close();
        if(n > 0){
            System.out.println("插入成功");
            return;
        }
        System.out.println("插入失败");
    }
}

